package view;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

import java.sql.*;
import java.util.*;
import java.util.List;

import dao.AdminDao;
import modle.Admin;
import modle.Country;
import util.StringUtil;


//管理员登录面板
public class Admin_Login extends JFrame {

	private JPanel contentPane;
	private JPasswordField A_PassWord;
	private JTextField A_UserName;
	private JLabel lblAdminLogin;
	private JLabel un_Label;
	private JLabel pw_Label;
	private JButton btnLogin;
	util.DbUtil dbUtil = new util.DbUtil();
	public static Admin s_currentUser = null;// 保存登陆用户的参数
	private JComboBox comboBox;
	private List<Country> listCountries;
	private Locale locale;
	private ResourceBundle rd;
	private JLabel backgroundlabel;
	private JButton btnBack;
	//-------------------ResourceBundle类（用于本地化或翻译成多种语言）--------------------------------
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Admin_Login frame = new Admin_Login();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Admin_Login() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(Admin_Login.class.getResource("/img/iconImage.jpg")));
		setTitle("Welcome to Food Corner");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 650, 449);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		un_Label = new JLabel("UserName: ");
		un_Label.setForeground(new Color(70, 130, 180));
		un_Label.setIcon(new ImageIcon(Admin_Login.class.getResource("/img/userName.png")));
		un_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 17));
		un_Label.setBounds(102, 119, 133, 26);
		contentPane.add(un_Label);
		
		A_UserName = new JTextField();
		A_UserName.setBounds(249, 121, 188, 26);
		contentPane.add(A_UserName);
		A_UserName.setColumns(10);
		
		A_PassWord = new JPasswordField();
		A_PassWord.setBounds(249, 169, 188, 26);
		contentPane.add(A_PassWord);
		
		pw_Label = new JLabel("PassWord: ");
		pw_Label.setForeground(new Color(70, 130, 180));
		pw_Label.setIcon(new ImageIcon(Admin_Login.class.getResource("/img/userName.png")));
		pw_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 17));
		pw_Label.setBounds(102, 173, 133, 26);
		contentPane.add(pw_Label);
		
		btnLogin = new JButton("Login");
		btnLogin.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 19));
		btnLogin.setBounds(265, 276, 133, 39);
		contentPane.add(btnLogin);
		btnLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("正在登录中......");
				loginActionPerformed(e);
			}
		});
		
//		管理员感觉应该不能在这里注册
//		JButton btnRegister = new JButton("Register");
//		btnRegister.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 19));
//		btnRegister.setBounds(397, 291, 133, 39);
//		contentPane.add(btnRegister);
//		btnRegister.addActionListener(new ActionListener() {
//			public void actionPerformed(ActionEvent e) {
//				regisiterActionPerformed();
//			}
//		});
		
		lblAdminLogin = new JLabel("Admin Login");
		lblAdminLogin.setForeground(new Color(205, 133, 63));
		lblAdminLogin.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 23));
		lblAdminLogin.setBounds(201, 40, 210, 39);
		contentPane.add(lblAdminLogin);
		
		comboBox = new JComboBox<>();						//组合按钮或可编辑字段和下拉列表的组件
		comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		comboBox.addItemListener(new ItemListener() {		//用于接收项目事件的侦听器接口。
			public void itemStateChanged(ItemEvent e) {
				int index = comboBox.getSelectedIndex();	//返回列表中与给定项目匹配的第一个项目。 
					String arr[] = listCountries.get(index).getId().split("-");					//  ???（应该是遇见 - 就分割）
					locale = new Locale(arr[0], arr[1]);//	???   Locale对象代表具体的地理，政治或文化地区。（第一个是语言，第二个是国家）
					rd = ResourceBundle.getBundle("resources.content", locale);		//使用指定的基本名称，区域设置和类加载器获取资源包（这里好像没用类加载器）。 
					
					//rd到底有什么用
					
					try {
						changeLanguage();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
			}
		});
		comboBox.setBounds(520, 13, 98, 32);
		contentPane.add(comboBox);
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("微软雅黑", Font.PLAIN, 19));
		btnBack.setBounds(14, 338, 89, 39);
		contentPane.add(btnBack);
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Start().setVisible(true);
				dispose();
			}
		});
		
		fillCountries();
		
	}
	
	private ImageIcon ResizeImage(String imgpath, JLabel label) {
		// TODO Auto-generated method stub
		ImageIcon img1 = new ImageIcon(Admin_Login.class.getResource(imgpath));
		Image img2 = img1.getImage();
		Image img3 = img2.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
		ImageIcon img4 = new ImageIcon(img3);
		return img4;
	}

	protected void loginActionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
//		validates();
		
		System.out.println("正在进入登录方法......");
		String UserName = A_UserName.getText();						//返回值为String
		String PassWord = new String(A_PassWord.getPassword());		//返回值为char[]
		
		if (StringUtil.isEmpty(UserName)) {
			JOptionPane.showMessageDialog(null, "用户名不能为空");
			return;
		}
		if (StringUtil.isEmpty(PassWord)) {
			JOptionPane.showMessageDialog(null, "密码不能为空");
			return;
		}
		
		System.out.println("用户名为：" + UserName + "  密码为：" + PassWord);
		
		Admin user = new Admin(UserName, PassWord);
		
		Connection con = null;
		try {
			con = dbUtil.getCon();
			AdminDao.isUserExist(con, user);
			Admin currentadmin = AdminDao.login(con, user);
			if (currentadmin != null) {
				System.out.println("YES");
				s_currentUser = currentadmin;// 保存登陆的用户
				new Admin_Menu().setVisible(true);
				this.dispose();
			} else {
				// 弹出提示信息
				JOptionPane.showMessageDialog(null, "用户名或密码错误");
			}
		}catch(Exception e1) {
			e1.printStackTrace();
			JOptionPane.showMessageDialog(null, "出现异常登录失败");
		}finally {
			try {
				// 关闭数据库连接
				dbUtil.closeCon(con);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
//	----------------------------------------------------------------------------------------------
	public void validates()
	{
		Border border;
		
		 for(Component c : getContentPane().getComponents())
		 {
			 if(c instanceof JTextField)
			 {
				 JTextField temp=((JTextField) c);
				 if(temp.getText().length()==0)
				 {
					//  create a line border with the specified color and width
				        border = BorderFactory.createLineBorder(Color.RED, 1);
				        
				        // set the border of this component
				        temp.setBorder(border);
				        temp.setToolTipText(temp.getName()+ rd.getString("errMsg"));
				 }
				 else
				 {
				        temp.setBorder(null);
				 }
			 }
		 }
	}
	
	private void fillCountries() {
		// TODO Auto-generated method stub
		listCountries = new ArrayList<Country>();
		listCountries.add(new Country("en-US", "English"));
		listCountries.add(new Country("zh-CN", "中文"));
		
		for(Country c : listCountries)
			comboBox.addItem(c.getName());
	}

	protected void changeLanguage() {
		// TODO Auto-generated method stub
		
		lblAdminLogin.setText(rd.getString("lblAdminLogin"));
		btnLogin.setText(rd.getString("btnLogin"));
		pw_Label.setText(rd.getString("pw_Label"));
		un_Label.setText(rd.getString("un_Label"));
		btnBack.setText(rd.getString("btnBack"));
	}
}
